<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Amap-官网方式</title>
</head>
<body>

<script type="text/javascript">
    window._AMapSecurityConfig = {
        securityJsCode: '5c2c03177c4918272773622a962ed977',
    }
</script>
<script type="text/javascript" src="https://webapi.amap.com/maps?v=2.0&key=f0905613f3af1fa969c4eaecf0bae0d2"></script>

<script>
    function locationSuccess(res) {
        console.log(res)
    }
</script>
<script>
    function getLocationAddress(lng, lat) {
        AMap.plugin('AMap.Geocoder', function () {
            var lnglat = [lng, lat]

            var geocoder = new AMap.Geocoder({})
            geocoder.getAddress(lnglat, function (status, result) {
                console.log(result)
                if (status === 'complete' && result.info === 'OK') {
                    const location = {}
                    location.lng = lng;
                    location.lat = lat

                    let addressComponent = result.regeocode.addressComponent;
                    location.city = addressComponent.city
                    location.district = addressComponent.district
                    location.province = addressComponent.province
                    location.street = addressComponent.street
                    location.streetNumber = addressComponent.streetNumber
                    location.township = addressComponent.township
                    location.address = result.regeocode.formattedAddress

                    locationSuccess(location)
                }
            })
        })
    }
</script>

<script>
    AMap.plugin('AMap.Geolocation', function () {
        var geolocation = new AMap.Geolocation({
            // 是否使用高精度定位，默认：true
            enableHighAccuracy: true,
            // 设置定位超时时间，默认：无穷大
            timeout: 10000
        })

        geolocation.getCurrentPosition(function (status, result) {
            if (status === 'complete') {
                onComplete(result)
            } else {
                onError(result)
            }
        });

        function onComplete(data) {
            // data是具体的定位信息
            console.log(data)
            getLocationAddress(data.position.lng, data.position.lat)
        }

        function onError(data) {
            // 定位出错
            console.error(data)
        }
    })
</script>

</body>
</html>
